﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SVC.client;

namespace UI.Forms
{
    public partial class ProductSale : FormBase1
    {
        //private SVC.client.KCSale_M m = null;
        private SVC.client.ProductSale_M m = null; //主表对象
        //private BindingList<SVC.client.View_BlankCards> bcs = null;
        //private BindingList<SVC.client.View_Goods_Lite> ds = null;
        private BindingList<SVC.client.Class1> ds = null; //明细表
        private string updjn = ""; //修改的单据号，区别该单据是新增还是修改
        public ProductSale(string djpre)
        {
            InitializeComponent();
            updjn = djpre;
        }

        private void btn_select_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (lue_ck.EditValue==null)
            {
                Comm.ShowAlert("请先选择仓库");
            }
            else
            {
                //通过仓库ID，查询产品
                Select_Product frm = new Select_Product(lue_ck.EditValue.ToString());
                frm.FatherRefresh = import;
                frm.ShowDialog();
            }
        }

        //绑定选中的产品信息
        void import(List<Product_Select> cs)
        {
            ds.Clear();
            foreach (Product_Select c in cs)
            {
                //SVC.client.ProductSale_D d = new SVC.client.ProductSale_D();
                Class1 d = new Class1();
                d.goodscode = c.GoodsCode;
                d.goodsname = c.GoodsName;
                d.unit = c.Unit;
                d.saleprice = c.outprice.Value; //参考售价
                d.jsprice = c.outprice.Value; //结算单价
                d.inprice = c.inprice.Value; //进价
                d.onhandcount = c.onhandcount.ToString(); //库存数
                d.lowprice = c.LowPrice.ToString(); //最低售价
                ds.Add(d);
            }


        }

        
        private void btn_OK_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dxValidationProvider1.Validate())
            {
                if (ds.Count==0)
                {
                    Comm.ShowAlert("请填写单据明细"); return;
                }
                m.djn = te_pid.Text.Trim(); //单据号
                m.remarks = te_remarks.Text.Trim(); //备注
                m.odate = dateEdit1.DateTime; //日期
                m.linkman = te_linkman.Text.Trim(); //联系人
                m.linktel = te_tel.Text.Trim(); //联系电话
                m.linkaddress = tel_address.Text.Trim(); //联系地址
                m.srpznum = txt_srpz.Text.Trim(); //收入凭证
                m.fpnum = txt_fphm.Text.Trim(); //发票号码
                m.cbpznum = txt_cbpz.Text.Trim(); //成本凭证编号
                m.cnnum = txt_cndh.Text.Trim(); //出纳单号
                
                if (lue_JSempid.EditValue != null)
                {
                    m.jsuser = new Guid(lue_JSempid.EditValue.ToString()); //经手人
                }
                m.createuser = new Guid(lue_opID.EditValue.ToString()); //制单人
                m.warehouseID = lue_ck.EditValue.ToString(); //仓库
                m.clientID = new Guid(lue_Client.EditValue.ToString()); //客户

                bool ischeck=false; //默认不需要审核
                string checkstatus = "已通过"; //不需要审核的，默认为已通过 
                foreach (Class1 pd in ds)
                {
                    //判断，只要有一个产品的结算金额小于了最低售价，则该销售单需要审核
                    if (pd.jsprice < decimal.Parse(pd.lowprice))
                    {
                        ischeck = true;
                        checkstatus = "待审核";
                    }
                }
                if (ischeck)
                {
                    DialogResult result = Comm.ShowDialog("销售明细中有销售金额小于最低售价，需要审核才能出库，是否继续");
                    if (result != DialogResult.OK)
                    {
                        return; //不是，就终止操作
                    }
                }
                m.ischeck = ischeck;
                m.checkstatus = checkstatus; //审核状态
                m.isfinish = false; //是否完结标志
                m.ysmoney = 0; //默认已收金额为0

                decimal total = 0, balance = 0, discount = 0;

                BindingList<ProductSale_D> pdlist = new BindingList<ProductSale_D>();
                foreach (Class1 item in ds)
                {
                    ProductSale_D pd = new ProductSale_D();
                    pd.djn = item.djn;
                    pd.goodscode = item.goodscode;
                    pd.goodsname = item.goodsname;
                    pd.inamount = item.inamount;
                    pd.inprice = item.inprice;
                    pd.jsamount = item.jsamount;
                    pd.jsprice = item.jsprice;
                    pd.count = item.count;
                    pd.remark = item.remark;
                    pd.saleamount = item.saleamount;
                    pd.saleprice = item.saleprice;
                    pd.unit = item.unit;
                    pdlist.Add(pd);
                    total += item.saleamount; //参考总售价
                    balance += item.jsamount; //实际总售价
                }
                m.ProductSale_D = pdlist;

                //m.total = decimal.Parse(gridColumn8.SummaryItem.SummaryValue.ToString()); //参考售价
                //m.banlance = decimal.Parse(gridColumn1.SummaryItem.SummaryValue.ToString()); //实际售价
                m.total = total;
                m.banlance = balance;
                m.discount = m.total - m.banlance; //折扣金额

                string r = "";
                if (updjn == "")
                {
                    r = my.bw.ProductSaleSave(m, my.ACID);
                    if (string.IsNullOrEmpty(r))
                    {
                        Comm.ShowInfo("新增销售出库单成功！");
                        this.Close();
                    }
                    else
                    {
                        Comm.ShowErorr(r);
                    }
                }
                else
                {
                    r = my.bw.ProductSale_UpdateSave(m, my.ACID);
                    if (string.IsNullOrEmpty(r))
                    {
                        Comm.ShowInfo("修改销售出库单成功！");
                        this.Close();
                    }
                    else
                    {
                        Comm.ShowErorr(r);
                    }
                }
            }
        }


        //窗体加载事件
        private void ProductSale_Load(object sender, EventArgs e)
        {
            bind(); 
            if (updjn == "") //新增
            {
                this.Text = "销售出库单-新增";
            }
            else
            {
                this.Text = "销售出库单-修改";
                SetProductInfo();
            }
           
        }
        /// <summary>
        /// 窗体加载时调用方法
        /// </summary>
        private void bind()
        {
            m = new SVC.client.ProductSale_M();
            ds = new BindingList<Class1>(); //实例化销售单明细
            lue_ck.Properties.DataSource = my.bw.Warehouse_Get("", my.ACID); //绑定仓库列表
            lue_Client.Properties.DataSource = my.bw.View_Client_lite_List(false, my.ACID); //客户列表
            lue_JSempid.Properties.DataSource = my.bw.View_Emp_lite_List("", my.ACID); //业务员列表
            lue_opID.Properties.DataSource = my.bw.View_Emp_lite_List("", my.ACID);
            lue_opID.EditValue = my.emp_lite.EmplID;
            lue_JSempid.EditValue = my.emp_lite.EmplID;
            gridControl1.DataSource = ds; 
            dateEdit1.EditValue = DateTime.Now;
        }

        //日期控件的值改变事件
        //自动生成单据号
        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (dateEdit1.EditValue == null) return;
            te_pid.Text = my.bw.getBillNO(my.emp_lite.shopcode, dateEdit1.DateTime, 13, my.ACID);
            m.djn = te_pid.Text;
            foreach (SVC.client.ProductSale_D d in ds)
            {
                d.djn = m.djn;
            }
        }

        private void lue_ck_EditValueChanged(object sender, EventArgs e)
        {
            ds.Clear();
            m.orderid = "";
        }

        private void lue_Client_EditValueChanged(object sender, EventArgs e)
        {
            
            m.orderid = "";
        }

        private void btn_orderImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        #region ** 单价数量值改变后自动计算总金额 **
        
        /// <summary>
        /// 计算总金额方法
        /// </summary>
        private void SaleAmount(string field)
        {
            try
            {

                Class1 d = gridView1.GetRow(gridView1.FocusedRowHandle) as Class1;
                string newvalue = "";
                if (gridView1.EditingValue != null)
                {
                    newvalue = gridView1.EditingValue.ToString();
                }
                else
                {
                    newvalue = gridView1.GetFocusedRowCellValue(field).ToString();
                }
                //判断是输入的哪个值
                switch (field)
                {
                    //case "saleprice":
                    //    d.saleprice = decimal.Parse(newvalue);
                    //    break;
                    case "jsprice":
                        d.jsprice = decimal.Parse(newvalue);
                        break;
                    case "count":
                        //判断，如果输入的数量大于了库存数，提示
                        if (decimal.Parse(newvalue) > decimal.Parse(d.onhandcount))
                        {
                            Comm.ShowAlert("库存数量不足！");
                            d.count = decimal.Parse(d.onhandcount);
                        }
                        else
                        {
                            d.count = decimal.Parse(newvalue);
                        }
                        break;
                    default:
                        break;
                }
                d.jsamount = d.jsprice * d.count;
                d.saleamount = d.saleprice * d.count;
            }
            catch
            {

            }

        }

        //private void rice_price_Leave(object sender, EventArgs e)
        //{
        //    SaleAmount("saleprice");
        //}

        private void rice_jsprice_Leave(object sender, EventArgs e)
        {
            SaleAmount("jsprice");
        }

        private void rise_quantity_Leave(object sender, EventArgs e)
        {
            SaleAmount("count");
        }

        #endregion


        #region 修改给控件赋值

        private void SetProductInfo()
        {
            ProductSale_M mitem = my.bw.GetPrductSale_M_ByID(updjn, my.ACID);
            lue_Client.EditValue = mitem.clientID;
            lue_ck.EditValue = mitem.warehouseID;
            dateEdit1.EditValue = mitem.odate;
            te_pid.EditValue = updjn;
            te_linkman.EditValue = mitem.linkman;
            te_tel.EditValue = mitem.linktel;
            tel_address.EditValue = mitem.linkaddress;
            txt_srpz.EditValue = mitem.srpznum;
            txt_fphm.EditValue = mitem.fpnum;
            txt_cbpz.EditValue = mitem.cbpznum;
            txt_cndh.EditValue = mitem.cnnum;
            te_remarks.EditValue = mitem.remarks;
            BindingList<View_ProductSale_D> viewds = my.bw.Get_ProductSale_D_By_M(updjn, my.ACID);
            foreach (View_ProductSale_D item in viewds)
            {
                Class1 pd = new Class1();
                pd.djn = item.djn;
                pd.goodscode = item.goodscode;  
                pd.goodsname = item.goodsname;
                pd.inamount = item.inamount;
                pd.inprice = item.inprice.Value;
                pd.jsamount = item.jsamount;
                pd.jsprice = item.jsprice;
                pd.count = item.count;
                pd.remark = item.remark;
                pd.saleamount = item.saleamount.Value;
                pd.saleprice = item.saleprice.Value;
                pd.unit = item.unit;
                pd.onhandcount = my.bw.GetonhandByMoreKey(item.goodscode, mitem.warehouseID, my.ACID).onhandcount.ToString();
                pd.lowprice = item.LowPrice.ToString();
                ds.Add(pd);
            }
            gridControl1.DataSource = ds;
        }

        #endregion

    }
}